<script setup>
import { ref, onMounted, computed } from 'vue'
import BottomNav from '@/components/BottomNav.vue'
import { getAll as getCoupons, gainCoupon } from '@/api/coupon'
import { ElMessage, ElLoading } from 'element-plus'


const loading = ref(false)

 //获取优惠券列表
const fetchCoupons = async () => {
   try {
     loading.value = true
     const res = await getCoupons() // ✅ 调用的是 coupon.js 的 getAll
    
     if (res.code === 1) {
       coupons.value = res.data.map(c => ({
         ...c,
         title: c.name,
         amount: c.value,
         condition: `满${c.minAmount}元可用`,
         isSoldOut: c.stock <= 0,
         isExpired: new Date(c.endTime) < new Date(),
         isReceived: c.used > 0, // 已领取或使用过
         shouldShow: c.status === 1 && c.used !== 2, // ✅ 控制是否展示
       }))
     }
   } catch (error) {
     ElMessage.error('获取优惠券失败')
   } finally {
     loading.value = false
   }
 }

// 领取优惠券
const receiveCoupon = async (coupon) => {
   if (coupon.isExpired || coupon.isReceived) return

   try {
     // ✅ 调用 coupon.js 中的 gainCoupon API
     const res = await gainCoupon(coupon.id)

     if (res.code === 1) {
       ElMessage.success('领取成功')

 // 更新优惠券状态
       const target = coupons.value.find(item => item.id === coupon.id)
       if (target) {
         target.receivedCount += 1
         target.isReceived = target.receivedCount >= coupon.receiveLimit
       }
     } else {
       ElMessage.error(res.msg || '领取失败')
     }
   } catch (error) {
     ElMessage.error('领取失败: ' + error.message)
   } finally {
     loadingInstance.close()
   }
 }

const getCouponButtonText = (coupon) => {
  if (coupon.isSoldOut) return '已售罄'
  if (coupon.isExpired) return '已过期'
  if (coupon.isReceived) return '已获取'
  return '立即领取'
}

onMounted(() => {
   fetchCoupons()
})

function formatDate(dateStr) {
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

function padZero(num) {
  return num < 10 ? `0${num}` : num
}

const filteredCoupons = computed(() => {
  return coupons.value.filter(coupon => coupon?.shouldShow)
})
</script>

<template>
  <div class="coupon-container">
    <!-- 顶部导航 -->
    <div class="coupon-header">
      <el-page-header @back="$router.back()" content="优惠券中心" />
    </div>

    <!-- 优惠券列表 -->
    <div class="coupon-list">
      <div
        v-for="coupon in filteredCoupons"
        :key="coupon.id"
        class="coupon-item"
        :class="{ 'coupon-disabled': coupon.isExpired || coupon.isReceived }"
        v-loading="loading"
      >
        <div class="coupon-content">
          <div class="coupon-left">
            <div class="coupon-amount">
              ¥<span>{{ coupon.value }}</span>
            </div>
            <div class="coupon-condition">满{{ coupon.minAmount }}元可用</div>
          </div>

          <div class="coupon-right">
            <div class="coupon-title">{{ coupon.name }}</div>
            <div class="coupon-time">有效期：{{ formatDate(coupon.startTime) }} 至 {{ formatDate(coupon.endTime) }}</div>
            
            <!-- 展示描述信息 -->
            <div class="coupon-desc" v-if="coupon.description">{{ coupon.description }}</div>

            <el-button
              type="primary"
              size="small"
              round
              :disabled="coupon.isExpired || coupon.isSoldOut || coupon.isReceived"
              @click="receiveCoupon(coupon)"
            >
              {{ getCouponButtonText(coupon) }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航 -->
    <BottomNav />
  </div>
</template>

<style scoped>
.coupon-container {
  padding-bottom: 60px;
  background: #f5f5f5;
  min-height: 100vh;
}

.coupon-header {
  padding: 15px;
  background: #fff;
  border-bottom: 1px solid #eee;
}

.coupon-list {
  padding: 12px;
}

.coupon-item {
  background: #fff;
  margin-bottom: 16px;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.coupon-disabled {
  opacity: 0.6;
}

.coupon-content {
  display: flex;
  padding: 16px;
}

.coupon-left {
  width: 100px;
  text-align: center;
  margin-right: 16px;
  border-right: 1px dashed #eee;
}

.coupon-amount {
  font-size: 24px;
  color: #ff6b6b;
  font-weight: bold;
}

.coupon-amount span {
  font-size: 32px;
}

.coupon-condition {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.coupon-right {
  flex: 1;
  position: relative;
}

.coupon-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.coupon-time {
  font-size: 12px;
  color: #999;
  margin-bottom: 12px;
}

.coupon-footer {
  position: absolute;
  right: 0;
  bottom: 0;
}

.coupon-desc {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
}
</style>